"""
    使用epoll完成一个IO多路复用的并发模型
    功能与select_server一致
"""
from select import *
from socket import *

# 创建几个IO对象
tcp_sock = socket()
tcp_sock.bind(("0.0.0.0", 2816))
tcp_sock.listen(5)

# 创建epoll对象
ep = epoll()

# 关注IO对象
ep.register(tcp_sock, EPOLLIN)

# 建立查找字典
map = {
    tcp_sock.fileno(): tcp_sock
}

print("开始监控IO")

while True:
    events = ep.poll()
    # 遍历就绪的IO
    for fd, event in events:
        if map[fd] is tcp_sock:
            conn, addr = map[fd].accept()
            print("Connect from", addr)
            conn.setblocking(False)
            ep.register(conn, EPOLLIN)
            map[conn.fileno()] = conn
        else:
            data = map[fd].recv(1024)
            if not data:
                ep.unregister(fd)
                map[fd].close()
                del map[fd]
                continue
            print(data.decode())
            map[fd].send(b"ok")
